package curator;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;

public class CuratorSet {
    private String IP="192.168.0.201:2181,192.168.0.202:2181,192.168.0.203:2181";
    CuratorFramework client;

    @Before
    public void createClient(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace("set")
                .build();
        client.start();
    }

    @Test
    public void test01() throws Exception {
        //更新节点
        Stat stat = client.setData()
                .forPath("/node1", "node111".getBytes());
        System.out.println(stat.getVersion());
        Thread.sleep(500);
    }

    @Test
    public void test02() throws Exception {
        client.setData()
                .withVersion(6)
                .forPath("/node1","nnnnn".getBytes());
        Thread.sleep(500);
    }

    @Test
    public void test03() throws Exception {
        //异步修改数据
        client.setData()
                .inBackground(new BackgroundCallback() {
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        // 节点的路径
                        System.out.println(event.getPath());
                        // 事件的类型
                        System.out.println(event.getType());
                    }
                })
                .forPath("/node1","ssss".getBytes());
        Thread.sleep(500);
    }


    @After
    public void closeClient(){
       client.close();
    }
}
